package com.groupsix.controller;

import com.groupsix.entity.Admin;
import com.groupsix.utils.PageInfo;
import com.groupsix.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 董盛昌
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: 管理员控制器
 * @date 2021/10/15 21:30
 */
@Controller
public class AdminController {
    // 依赖注入
    @Autowired
    private AdminService adminService;
    /**
     * 用户登录
     * 将提交数据(username,password)写入Admin对象
     */
    @RequestMapping("/login.action")
    public String login(Admin admin, Model model, HttpSession session, HttpServletRequest request) {
        Admin ad = adminService.findAdmin(admin);
        if(ad!=null){
            session.setAttribute("ad", ad);
            return "homepage";
        }
        model.addAttribute("msg", "用户名或密码错误，请重新登录！");
        return "login";

    }

    /**
     * 退出登录
     */
    @RequestMapping("/loginOut.action")
    public String loginOut(Admin admin, Model model, HttpSession session) {
        session.invalidate();
        return "login";

    }

    /**
     * 分页查询
     */
    @RequestMapping("/findAdmin.action")
    public String findAdmin(String username, String describe,Integer pageIndex,
                            Integer aid ,Integer pageSize,Model model) {

        PageInfo ai = adminService.findPageInfo(username,describe,
                aid,pageIndex,pageSize);
        model.addAttribute("ai",ai);
        return "admin_list";
    }


    /**
     * 添加管理员信息
     */
    @RequestMapping("/addAdmin.action")
    @ResponseBody
    public String addAdmin( @RequestBody Admin admin) {

        int a = adminService.addAdmin(admin);
        return "admin_list";
    }

    /**
     * 删除管理员信息；将请求体aId写入参数aId
     */
    @RequestMapping( "/deleteAdmin.action")
    @ResponseBody
    public String deleteAdmin(Integer aId) {
        int a = adminService.deleteAdmin(aId);
        return "admin_list";
    }

    /**
     * 修改管理员信息
     */
    /**
     * 将提交数据(aid,username...)写入Admin对象
     */
    @RequestMapping("/updateAdmin.action")
    public String updateAdmin(Admin admin) {
        int a = adminService.updateAdmin(admin);
        return "redirect:/findAdmin.action";
    }


    /**
     * 根据管理员Id搜索;将请求数据aid写入参数aid
     */
    @RequestMapping( "/findAdminById.action")
    public String findAdminById(Integer aId, HttpSession session) {
        Admin a= adminService.findAdminById(aId);
        session.setAttribute("a",a);
        return "admin_edit";
    }
}
